package demo.execises;

import java.util.Arrays;
import java.util.Comparator;

/**
 * @author yulian174
 * @version 1.0
 * 自定义Book类，里面包含name和price，按price排序(从大到小)。
 * 要求使用两种方式排序，有一个 Book[] books = 4本书对象.
 * 实现Comparator接口匿名内部类，也称为定制排序。
 * 按照 price(1)从大到小(2)从小到大(3)按照书名长度从大到小
 */
public class Book {
    public static void main(String[] args) {
        Book[] books = new Book[4];
        books[0] = new Book("安徒生童话", 12.58);
        books[1] = new Book("一千零一夜", 8.59);
        books[2] = new Book("鲁滨逊漂流记", 25.5);
        books[3] = new Book("哈利波特", 17.5);
        Book.sorted(books, new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                Book b1 = (Book) o1;
                Book b2 = (Book) o2;
                int n = (int) (b2.price - b1.price);
                return n;
            }
        });
        Book.prin(books);
        Book.sorted(books, new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                Book b1 = (Book) o1;
                Book b2 = (Book) o2;
                int n = (int) (b1.price - b2.price);
                return n;
            }
        });
        Book.prin(books);
        Book.sorted(books, new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                Book b1 = (Book) o1;
                Book b2 = (Book) o2;
                int n = (int) (b2.name.length() - b1.name.length());
                return n;
            }
        });
        Book.prin(books);
    }

    private String name;
    private double price;

    public Book(String name, double price) {
        this.name = name;
        this.price = price;
    }

    public static void sorted(Book[] book, Comparator e) {
        Book temp = null;
        for (int i = 0; i < book.length - 1; i++) {
            for (int j = 0; j < book.length - i - 1; j++) {
                if (e.compare(book[j], book[j + 1]) > 0) {
                    temp = book[j];
                    book[j] = book[j + 1];
                    book[j + 1] = temp;
                }
            }
        }
    }

    public static void prin(Book[] book) {
        for (int i = 0; i < book.length; i++) {
            System.out.print(book[i].name + " ");
            System.out.print(book[i].price + " ");
            System.out.println();
        }
        System.out.println();
    }
}
